<?php
namespace Modules\Base\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Modules\Base\Entities\Basereply;
use Modules\Base\Http\Requests\BasereplyRequest;
use DB;
use Modules\Wachat\Entities\Wxkeywords;
use Modules\Wachat\Entities\Wxrule;

class BasereplyController extends Controller
{
    //显示列表
    public function index()
    {
        $data = Basereply::paginate(10);
        return view('base::basereply.index', compact('data'));
    }

    //创建视图
    public function create(Basereply $basereply,WechatService $wechatService)
    {
        $view = $wechatService->rule();
        return view('base::basereply.create',compact('basereply','view'));
    }

    //保存数据
    public function store(BasereplyRequest $request,Basereply $basereply,WechatService $wechatService)
    {
        //$post = json_decode($request->input('rule'),true);
        //使用实务关联来判断是否全部成功，如果有一个不成功，则认为全部不成功！
        //DB::beginTransaction();
            //将规则数据存入规则表
            //$rule = Wxrule::create([
            //    'name' => $post['name'],
            //    'module' => \HDModule::currentModule(),
            //]);
            //将关键词数据存入到关联的关键词表中
            //foreach ($post['keywords'] as $v){
            //    Wxkeywords::create([
            //       'key' => $v['key'],
            //       'rule_id' => $rule['id'],
            //    ]);
            //}
            //dd($request->all());
            //将回复数据存入Basereply表，并且转换成数组
            //$contents = $post['keywords'];
            //dd($contents);
            //foreach ($contents as $v){
            //    Basereply::create([
            //        'content' => $v['content'],
            //        'rule_id' => $rule['id'],
            //    ]);
            //}
        //DB::commit();
        //调用服务类的规则和关键词方法
        $rule = $wechatService->SaveRule();
        //添加回复内容
        Basereply::create([
            'content' => $request->input('content'),
            'rule_id' => $rule['id'],
        ]);
        return redirect('/base/basereply')->with('success', '保存成功');
    }

    //显示记录
    public function show(Basereply $field)
    {
        return view('base::basereply.show', compact('field'));
    }

    //编辑视图
    public function edit(Basereply $basereply,WechatService $wechatService)
    {
        $view = $wechatService->rule($basereply['rule_id']);
        return view('base::basereply.edit', compact('basereply','view'));
    }

    //更新数据
    public function update(BasereplyRequest $request, Basereply $basereply,WechatService $wechatService)
    {
        //调用服务类的规则和关键词方法
        $rule = $wechatService->SaveRule($basereply['rule_id']);

        return redirect('/base/basereply')->with('success','更新成功');
    }

    //删除模型
    public function destroy(Basereply $basereply)
    {
        //删除规则表
        Wxrule::destroy($basereply['rule_id']);
        $basereply->delete();
        return redirect('base/basereply')->with('success','删除成功');
    }
}
